<?php
/**
 * 首页接口文件
 * @author maniac
 */
namespace app\api\controller\v1;


use app\common\model\CustomerService;

use app\common\model\Goods as GoodsModel;
use app\common\model\News;


use app\common\model\PointsLog;
use app\common\model\test;
use app\common\model\WechatUsers;
use app\common\service\Wechat;
use app\facade\Aes as AesFacade;
use app\facade\Options;
use app\facade\Slides;
use think\Db;
use think\Exception;


class Index extends Base
{
    //兑礼计划
    public function cashPlan(){
        //兑礼方式
        $data['mode'] = News::where("id",1)->value('content');
        //兑礼细则
        $data['rule'] = News::where("id",2)->value('content');
        return j(0,"成功",$data);
    }
    //贵宾尊享
    public function VipEnjoy(){
        $data = News::where("id",4)->value('content');
        $ad_img = Slides::slides(2,'','id,image_id,title,description');
        return j(0,"成功",[
            'ad_img' => $ad_img,
            'data' => $data
        ]);
    }
    //积分管理初始化
    public function pointsManagementInit(){
        $user_id = $this->checkUserToken();
        //会员信息
        $data = \app\common\model\Members::where("id",$user_id)->field('id,username,mobile,image_uri,points,role_id')->append(['role_icon_url'])->find();
        //客服电话
        $info = Options::option('site_info');
        $info = $info ? unserialize($info) : [];
        $data['customer_service'] = $info['site_phone'];
        //积分规则
        //会员积分
        $data['member_points'] = News::where("id",5)->field('id,smalltext,content')->find();
        //积分政策
        $data['integral_policy'] = News::where("id",6)->field('id,smalltext,content')->find();
        return j(0,"成功",$data);
    }
    //积分明细
    public function pointsLogList(){
        $user_id = $this->checkUserToken();
        $limit = input('limit');
        $page = input('page');
        $where = [
            ["member_id","eq",$user_id],
            ["status","eq",1]
        ];
        $data = (new PointsLog())->getList($where,true,'created_at',[],$page,$limit);
        return j(0,"成功",$data);
    }
    //入会方式
    public function waysJoin(){
        $data = News::where("id",7)->find();
        $data['content'] = str_replace('src="/static/', 'src="'.config('system.attach_uri_prefix').'static/', $data['content']);;
        return j(0,"成功",$data);
    }
    //产品兑换初始化
    public function cashGoodsListInit(){
        $user_id = $this->checkUserToken();
        $limit = input('limit');
        $page  = input('page');
        //会员信息
        $member_info = \app\common\model\Members::where("id",$user_id)->field('id,points,role_id')->append(['role_icon_url'])->find();
        //获取分类
        $goods_category = \app\common\model\GoodCategory::where("is_show",1)->order('list_order desc')->field('id,name')->select();
        $data = GoodsModel::limit( ($page - 1)*$limit,$limit)->where('category_id',$goods_category[0]['id'])
            ->field('id,goods_name,goods_thumb_id,sale_price')->order('list_order desc,sale_price asc')->append(['image_uri'])->select();
        return j(0,"成功",[
            'member_info' => $member_info,
            'goods_category' => $goods_category,
            'data' => $data,
        ]);
    }
    //绑定手机号
    public function bindingMobile($mobile,$user_id){


            $member = \app\common\model\Members::where("mobile",$mobile)->where("create_type",1)->find();
            if (!empty($member)){
                //用户是否绑定
                if ($member['is_binding']){
                    if ($member['id'] == $user_id){
                        \exception("已绑定手机号,不可重复绑定");
                    }
                    exception("当前手机号已被绑定");
                }
                $member_info = \app\common\model\Members::where("id",$user_id)->find();
                //更新后台录入会员数据
                \app\common\model\Members::where("id",$member['id'])->update([
                    'wechat_id' => $member_info['wechat_id'],
                    'nickname' => $member_info['nickname'],
                    'image_uri' => $member_info['image_uri'],
                    'openid' => $member_info['username'],
                    'is_binding' => 1,
                ]);
                //更新微信用户数据
                WechatUsers::where("id",$member_info['wechat_id'])->update([
                    'member_id' => $member['id']
                ]);
                //重新生成userToken
                $encrypt = [
                    'id' => $member['id'],
                ];
            }else{
                //添加手机号
                \app\common\model\Members::where("id",$user_id)->update([
                    'mobile' => $mobile
                ]);
                //重新生成userToken
                $encrypt = [
                    'id' => $user_id,
                ];
            }
            $userToken = AesFacade::encrypt(http_build_query($encrypt));
            return $userToken;

    }
    //生日提醒
    public function birthdayReminder(){
        $time = date("m-d");
        $where = [
            ["is_binding","eq",1],
            ["birthday","like","%".$time."%"]
        ];
        try {
            $member = \app\common\model\Members::where($where)->field('id,openid,username,wechat_id,birthday,mobile')->append(['sex_txt'])->select();
            foreach ($member as $key => $value){
                //统一服务消息
                $message = [
                    'first'        => ['value' => '亲爱的用户'], //头
                    'keyword1'     => ['value' => $member['username']], //姓名
                    'keyword2'     => ['value' => $member['sex_txt']],  //性别
                    'keyword3'     => ['value' => $member['birthday']],  //生日
                    'keyword4'     => ['value' => $member['mobile']],  //手机
                    'remark'       => ['value' => '祝您生日快乐！'], //尾
                ];
                $url = '/pages/index/index';
                //发送模板消息
                (new Wechat())->sendMessageAll($value['openid'],'R8c56BuJVEr5Mrc4VMLbbVJpo_QVOMZgJbdU_uwGyW0',$message,'wxc88926430f17f6b2',$url);
                sleep(1);
            }
            return j(0,"执行成功");
        } catch (Exception $exception) {
            return j(1,$exception->getMessage());
        }
    }
}
